

import React, { useState, useCallback } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, Modal, Alert, RefreshControl, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';
import ApprovalTaskItem from './components/ApprovalTaskItem';
import FilterModal from './components/FilterModal';

interface ApprovalTask {
  id: string;
  title: string;
  applicant: string;
  department: string;
  time: string;
  currentNode: string;
  priority: 'high' | 'medium' | 'low';
  processId: string;
}

const PENDING_APPROVAL_DATA: ApprovalTask[] = [
  {
    id: 'task-001',
    title: '员工请假申请',
    applicant: '李小红',
    department: '技术部',
    time: '2024-01-15 14:30',
    currentNode: '部门经理审批',
    priority: 'high',
    processId: 'proc-001',
  },
  {
    id: 'task-002',
    title: '采购申请单',
    applicant: '王强',
    department: '采购部',
    time: '2024-01-15 10:15',
    currentNode: '财务审批',
    priority: 'medium',
    processId: 'proc-002',
  },
  {
    id: 'task-003',
    title: '项目预算申请',
    applicant: '陈思',
    department: '项目部',
    time: '2024-01-14 16:45',
    currentNode: '管理层审批',
    priority: 'low',
    processId: 'proc-003',
  },
  {
    id: 'task-004',
    title: '出差申请',
    applicant: '刘敏',
    department: '市场部',
    time: '2024-01-14 09:30',
    currentNode: '部门经理审批',
    priority: 'medium',
    processId: 'proc-004',
  },
  {
    id: 'task-005',
    title: '设备维修申请',
    applicant: '赵刚',
    department: '运维部',
    time: '2024-01-13 15:20',
    currentNode: '行政审批',
    priority: 'low',
    processId: 'proc-005',
  },
];

const PendingApprovalScreen: React.FC = () => {
  const router = useRouter();
  const [searchText, setSearchText] = useState('');
  const [selectedTaskIds, setSelectedTaskIds] = useState<Set<string>>(new Set());
  const [isBatchMode, setIsBatchMode] = useState(false);
  const [isFilterModalVisible, setIsFilterModalVisible] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [approvalTasks, setApprovalTasks] = useState<ApprovalTask[]>(PENDING_APPROVAL_DATA);

  const handleSearchTextChange = useCallback((text: string) => {
    setSearchText(text);
  }, []);

  const handleFilterButtonPress = useCallback(() => {
    setIsFilterModalVisible(true);
  }, []);

  const handleSortButtonPress = useCallback(() => {
    setIsFilterModalVisible(true);
  }, []);

  const handleTaskPress = useCallback((processId: string) => {
    if (isBatchMode) return;
    router.push(`/p-approval_detail?processInstanceId=${processId}`);
  }, [isBatchMode, router]);

  const handleTaskCheckboxToggle = useCallback((taskId: string) => {
    setSelectedTaskIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(taskId)) {
        newSet.delete(taskId);
      } else {
        newSet.add(taskId);
      }
      return newSet;
    });
  }, []);

  const handleCancelBatchMode = useCallback(() => {
    setSelectedTaskIds(new Set());
    setIsBatchMode(false);
  }, []);

  const handleBatchApprove = useCallback(() => {
    if (selectedTaskIds.size === 0) return;
    
    Alert.alert(
      '批量操作',
      `确定要批量通过选中的 ${selectedTaskIds.size} 个审批吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            console.log('批量通过:', Array.from(selectedTaskIds));
            Alert.alert('提示', '批量通过成功');
            handleCancelBatchMode();
          },
        },
      ]
    );
  }, [selectedTaskIds.size, handleCancelBatchMode]);

  const handleBatchReject = useCallback(() => {
    if (selectedTaskIds.size === 0) return;
    
    Alert.alert(
      '批量操作',
      `确定要批量驳回选中的 ${selectedTaskIds.size} 个审批吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            console.log('批量驳回:', Array.from(selectedTaskIds));
            Alert.alert('提示', '批量驳回成功');
            handleCancelBatchMode();
          },
        },
      ]
    );
  }, [selectedTaskIds.size, handleCancelBatchMode]);

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    // 模拟刷新数据
    setTimeout(() => {
      setIsRefreshing(false);
      console.log('列表已刷新');
    }, 1000);
  }, []);

  const handleFilterModalClose = useCallback(() => {
    setIsFilterModalVisible(false);
  }, []);

  const handleApplyFilter = useCallback((filters: any, sort: string) => {
    console.log('应用筛选条件:', filters);
    console.log('排序方式:', sort);
    setIsFilterModalVisible(false);
  }, []);

  React.useEffect(() => {
    setIsBatchMode(selectedTaskIds.size > 0);
  }, [selectedTaskIds.size]);

  const filteredTasks = approvalTasks.filter(task => {
    const searchLower = searchText.toLowerCase();
    return (
      task.title.toLowerCase().includes(searchLower) ||
      task.applicant.toLowerCase().includes(searchLower) ||
      task.department.toLowerCase().includes(searchLower)
    );
  });

  const renderApprovalTask = useCallback(({ item }: { item: ApprovalTask }) => (
    <ApprovalTaskItem
      task={item}
      isSelected={selectedTaskIds.has(item.id)}
      isBatchMode={isBatchMode}
      onPress={() => handleTaskPress(item.processId)}
      onCheckboxToggle={() => handleTaskCheckboxToggle(item.id)}
    />
  ), [selectedTaskIds, isBatchMode, handleTaskPress, handleTaskCheckboxToggle]);

  const renderEmptyState = useCallback(() => (
    <View style={styles.emptyStateContainer}>
      <View style={styles.emptyStateIcon}>
        <FontAwesome5 name="check-circle" size={48} color="#9CA3AF" />
      </View>
      <Text style={styles.emptyStateTitle}>暂无待办审批</Text>
      <Text style={styles.emptyStateDescription}>您当前没有需要处理的审批任务</Text>
    </View>
  ), []);

  const renderListHeader = useCallback(() => (
    <View style={styles.listHeaderContainer}>
      {/* 批量选择模式提示 */}
      {isBatchMode && (
        <View style={styles.batchSelectTip}>
          <Text style={styles.batchSelectTipText}>
            已选择 <Text style={styles.selectedCount}>{selectedTaskIds.size}</Text> 项
          </Text>
          <TouchableOpacity onPress={handleCancelBatchMode}>
            <Text style={styles.cancelBatchText}>取消</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  ), [isBatchMode, selectedTaskIds.size, handleCancelBatchMode]);

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <Text style={styles.pageTitle}>待我审批</Text>
          <View style={styles.headerActions}>
            <TouchableOpacity style={styles.headerButton} onPress={handleFilterButtonPress}>
              <FontAwesome6 name="filter" size={18} color="#6B7280" />
            </TouchableOpacity>
            <TouchableOpacity style={styles.headerButton} onPress={handleSortButtonPress}>
              <FontAwesome6 name="sort" size={18} color="#6B7280" />
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 搜索框 */}
        <View style={styles.searchContainer}>
          <View style={styles.searchInputWrapper}>
            <FontAwesome6 name="magnifying-glass" style={styles.searchIcon} />
            <TextInput
              style={styles.searchInput}
              placeholder="搜索审批标题、发起人..."
              value={searchText}
              onChangeText={handleSearchTextChange}
              placeholderTextColor="#9CA3AF"
            />
          </View>
        </View>
      </View>

      {/* 主要内容区域 */}
      <FlatList
        data={filteredTasks}
        renderItem={renderApprovalTask}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={renderListHeader}
        ListEmptyComponent={renderEmptyState}
        contentContainerStyle={styles.listContentContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            colors={['#969FFF']}
            tintColor="#969FFF"
          />
        }
      />

      {/* 批量操作底部栏 */}
      {isBatchMode && (
        <View style={styles.batchActionsContainer}>
          <TouchableOpacity
            style={[styles.batchActionButton, styles.approveButton]}
            onPress={handleBatchApprove}
            disabled={selectedTaskIds.size === 0}
          >
            <LinearGradient
              colors={['#969FFF', '#5147FF']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.batchActionGradient}
            >
              <FontAwesome6 name="check" size={16} color="#FFFFFF" />
              <Text style={styles.batchActionText}>批量通过</Text>
            </LinearGradient>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.batchActionButton, styles.rejectButton]}
            onPress={handleBatchReject}
            disabled={selectedTaskIds.size === 0}
          >
            <FontAwesome6 name="xmark" size={16} color="#FFFFFF" />
            <Text style={styles.batchActionText}>批量驳回</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* 筛选/排序弹窗 */}
      <FilterModal
        visible={isFilterModalVisible}
        onClose={handleFilterModalClose}
        onApply={handleApplyFilter}
      />
    </SafeAreaView>
  );
};

export default PendingApprovalScreen;

